// pages/reading/reading.js
Page({
  data: {
    bookTitle: '森林里的故事',
    currentPage: 1,
    totalPages: 10,
    progress: 10,
    currentText: 'Once upon a time, in a magical forest...',
    currentTranslation: '很久很久以前，在一个神奇的森林里...',
    showTranslation: false,
    isPlaying: false,
    showFontPanel: false,
    autoPlay: false,
    fontSize: 'medium',
    // 设置相关数据
    showSettings: false,
    readMode: 'image', // image 或 text
    autoPlayAudio: false,
    autoFlip: false,
    autoNextBook: false,
    showTranslationSetting: false,
    flipEffect: 'slide', // slide 或 none
    loopCurrentBook: false,
    playbackRate: '1.0', // 0.5, 0.75, 1.0, 1.25, 1.5
    pages: [
      {
        text: 'Once upon a time, in a magical forest...',
        translation: '很久很久以前，在一个神奇的森林里...'
      },
      {
        text: 'There lived a little fox who loved to explore.',
        translation: '住着一只喜欢探索的小狐狸。'
      },
      {
        text: 'Every day, the fox would wander through the trees.',
        translation: '每天，狐狸都会在树林中漫步。'
      },
      {
        text: 'He would meet his friends: a wise owl and a friendly rabbit.',
        translation: '他会遇到他的朋友们：一只聪明的猫头鹰和一只友好的兔子。'
      },
      {
        text: 'Together, they would share stories and adventures.',
        translation: '他们一起分享故事和冒险。'
      },
      {
        text: 'The owl would tell them about the stars and the moon.',
        translation: '猫头鹰会告诉他们关于星星和月亮的故事。'
      },
      {
        text: 'The rabbit would show them the best places to find carrots.',
        translation: '兔子会向他们展示找到胡萝卜的最佳地点。'
      },
      {
        text: 'And the fox would lead them on exciting journeys.',
        translation: '而狐狸会带领他们进行激动人心的旅程。'
      },
      {
        text: 'They learned that friendship makes every day special.',
        translation: '他们学会了友谊让每一天都变得特别。'
      },
      {
        text: 'And so, they lived happily ever after in their magical forest.',
        translation: '于是，他们在神奇的森林里幸福地生活着。'
      }
    ],
    audioContext: null,
    flipping: false, // 翻页动画class
    isRecording: false,
    hasRecord: false,
    recordFilePath: '',
    showFinishModal: false,
    recordTimer: null,
    recordDuration: 0,
    maxRecordDuration: 30, // 秒
  },

  onLoad(options) {
    const { id, title } = options
    if (title) {
      this.setData({
        bookTitle: title
      })
    }
    
    this.loadPage(1)
    this.loadSettings()
    // 初始化音频
    this.initAudio()
  },

  // 初始化音频
  initAudio() {
    if (this.data.audioContext) {
      this.data.audioContext.destroy()
    }
    const audio = wx.createInnerAudioContext()
    audio.obeyMuteSwitch = false
    this.setData({ audioContext: audio })
  },

  // 加载页面内容
  loadPage(pageNum) {
    const page = this.data.pages[pageNum - 1]
    if (page) {
      this.setData({
        currentPage: pageNum,
        currentText: page.text,
        currentTranslation: page.translation,
        progress: (pageNum / this.data.totalPages) * 100
      })
      // 翻页动画
      this.setData({ flipping: true })
      setTimeout(() => { this.setData({ flipping: false }) }, 400)
      // 自动播放音频
      if (this.data.autoPlayAudio) {
        this.playAudio()
      } else {
        this.stopAudio()
      }
      // 自动翻页
      this.setupAutoFlip()
    }
  },

  // 播放音频
  playAudio() {
    const audio = this.data.audioContext
    if (!audio) return
    // 假设音频文件名为 audio/page{n}.mp3
    const src = `/audio/page${this.data.currentPage}.mp3`
    audio.src = src
    audio.playbackRate = parseFloat(this.data.playbackRate)
    audio.play()
    this.setData({ isPlaying: true })
    audio.onEnded(() => {
      this.setData({ isPlaying: false })
    })
  },

  // 停止音频
  stopAudio() {
    const audio = this.data.audioContext
    if (audio) {
      audio.stop()
      this.setData({ isPlaying: false })
    }
  },

  // 切换播放状态
  togglePlay() {
    const audio = this.data.audioContext
    if (!audio) return
    if (this.data.isPlaying) {
      audio.pause()
      this.setData({ isPlaying: false })
    } else {
      this.playAudio()
    }
  },

  // 切换自动播放
  toggleAutoPlay() {
    this.setData({
      autoPlay: !this.data.autoPlay
    })
    
    if (this.data.autoPlay) {
      this.startAutoPlay()
    } else {
      this.stopAutoPlay()
    }
  },

  // 开始自动播放
  startAutoPlay() {
    this.autoPlayTimer = setInterval(() => {
      if (this.data.currentPage < this.data.totalPages) {
        this.nextPage()
      } else {
        this.stopAutoPlay()
      }
    }, 3000)
  },

  // 停止自动播放
  stopAutoPlay() {
    if (this.autoPlayTimer) {
      clearInterval(this.autoPlayTimer)
      this.autoPlayTimer = null
    }
  },

  // 切换字体大小面板
  toggleFontSize() {
    this.setData({
      showFontPanel: !this.data.showFontPanel
    })
  },

  // 设置字体大小
  setFontSize(e) {
    const size = e.currentTarget.dataset.size
    this.setData({
      fontSize: size,
      showFontPanel: false
    })
    
    // 根据字体大小调整样式
    let fontSize = 24
    switch (size) {
      case 'small':
        fontSize = 18
        break
      case 'large':
        fontSize = 32
        break
      default:
        fontSize = 24
    }
    
    // 这里可以通过设置样式来改变字体大小
    wx.showToast({
      title: `字体大小已调整为${size === 'small' ? '小' : size === 'large' ? '大' : '中'}`,
      icon: 'none'
    })
  },

  // 上一页
  prevPage() {
    if (this.data.currentPage > 1) {
      this.loadPage(this.data.currentPage - 1)
    }
  },

  // 下一页
  nextPage() {
    if (this.data.currentPage < this.data.totalPages) {
      this.loadPage(this.data.currentPage + 1)
    } else {
      // 阅读完成
      if (this.data.loopCurrentBook || this.data.autoNextBook) {
        this.handleBookEnd()
      } else {
        wx.showModal({
          title: '阅读完成',
          content: '恭喜你完成了这本绘本的阅读！',
          showCancel: false,
          success: () => { wx.navigateBack() }
        })
      }
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 自动翻页定时器
  setupAutoFlip() {
    if (this.autoFlipTimer) {
      clearTimeout(this.autoFlipTimer)
      this.autoFlipTimer = null
    }
    if (this.data.autoFlip) {
      this.autoFlipTimer = setTimeout(() => {
        if (this.data.currentPage < this.data.totalPages) {
          this.nextPage()
        } else {
          // 结束时处理自动阅读下一本/循环
          this.handleBookEnd()
        }
      }, 3000)
    }
  },

  // 处理绘本结束后的自动跳转/循环
  handleBookEnd() {
    if (this.data.loopCurrentBook) {
      this.loadPage(1)
    } else if (this.data.autoNextBook) {
      wx.showToast({ title: '自动跳转到下一个绘本（示例）', icon: 'none' })
      // 这里可实现实际跳转逻辑
    } else {
      this.setData({ showFinishModal: true })
    }
  },
  readAgain() {
    this.setData({ showFinishModal: false })
    this.loadPage(1)
  },
  readNext() {
    this.setData({ showFinishModal: false })
    wx.showToast({ title: '跳转到下一本（示例）', icon: 'none' })
    // 这里可实现实际跳转逻辑
  },

  // 页面卸载时清理定时器和音频
  onUnload() {
    this.stopAutoPlay()
    if (this.autoFlipTimer) {
      clearTimeout(this.autoFlipTimer)
      this.autoFlipTimer = null
    }
    if (this.data.audioContext) {
      this.data.audioContext.destroy()
    }
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: `${this.data.bookTitle} - 儿童英语分级阅读`,
      path: '/pages/reading/reading'
    }
  },

  // ========== 设置相关方法 ==========

  // 加载设置
  loadSettings() {
    try {
      const settings = wx.getStorageSync('readingSettings')
      if (settings) {
        this.setData({
          readMode: settings.readMode || 'image',
          autoPlayAudio: settings.autoPlayAudio || false,
          autoFlip: settings.autoFlip || false,
          autoNextBook: settings.autoNextBook || false,
          showTranslationSetting: settings.showTranslationSetting || false,
          flipEffect: settings.flipEffect || 'slide',
          loopCurrentBook: settings.loopCurrentBook || false,
          playbackRate: settings.playbackRate || '1.0'
        })
      }
    } catch (e) {
      console.log('加载设置失败:', e)
    }
  },

  // 保存设置
  saveSettings() {
    try {
      const settings = {
        readMode: this.data.readMode,
        autoPlayAudio: this.data.autoPlayAudio,
        autoFlip: this.data.autoFlip,
        autoNextBook: this.data.autoNextBook,
        showTranslationSetting: this.data.showTranslationSetting,
        flipEffect: this.data.flipEffect,
        loopCurrentBook: this.data.loopCurrentBook,
        playbackRate: this.data.playbackRate
      }
      wx.setStorageSync('readingSettings', settings)
    } catch (e) {
      console.log('保存设置失败:', e)
    }
  },

  // 显示设置窗口
  showSettings() {
    this.setData({ showSettings: true });
  },

  // 隐藏设置窗口
  hideSettings() {
    this.setData({
      showSettings: false
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 阅读模式切换
  onReadModeChange(e) {
    const mode = e.detail.value
    this.setData({
      readMode: mode
    })
    this.saveSettings()
    
    wx.showToast({
      title: `已切换到${mode === 'image' ? '图片' : '文字'}模式`,
      icon: 'none'
    })
  },

  // 音频自动播放切换
  onAutoPlayAudioChange(e) {
    this.setData({
      autoPlayAudio: e.detail.value
    })
    this.saveSettings()
  },

  // 自动翻页切换
  onAutoFlipChange(e) {
    this.setData({
      autoFlip: e.detail.value
    })
    this.saveSettings()
  },

  // 自动阅读下一本切换
  onAutoNextBookChange(e) {
    this.setData({
      autoNextBook: e.detail.value
    })
    this.saveSettings()
  },

  // 查看翻译切换
  onShowTranslationChange(e) {
    this.setData({
      showTranslationSetting: e.detail.value
    })
    this.saveSettings()
  },

  // 翻页效果切换
  onFlipEffectChange(e) {
    const effect = e.detail.value
    this.setData({
      flipEffect: effect
    })
    this.saveSettings()
  },

  // 单绘本循环切换
  onLoopCurrentBookChange(e) {
    this.setData({
      loopCurrentBook: e.detail.value
    })
    this.saveSettings()
  },

  // 播放速度切换
  onPlaybackRateChange(e) {
    const rate = e.currentTarget.dataset.rate
    this.setData({ playbackRate: rate })
    this.saveSettings()
    // 实时调整音频速率
    if (this.data.audioContext) {
      this.data.audioContext.playbackRate = parseFloat(rate)
    }
    wx.showToast({ title: `播放速度已调整为${rate}x`, icon: 'none' })
  },

  // 切换录音状态
  toggleRecord() {
    if (this.data.isRecording) {
      this.stopRecord()
    } else {
      this.startRecord()
    }
  },

  // 开始录音
  startRecord() {
    if (this.data.isPlaying) {
      this.stopAudio()
    }
    const recorder = wx.getRecorderManager()
    recorder.onStart(() => {
      this.setData({ isRecording: true, recordDuration: 0 })
      this.recordTimer = setInterval(() => {
        this.setData({ recordDuration: this.data.recordDuration + 1 })
        if (this.data.recordDuration >= this.data.maxRecordDuration) {
          this.stopRecord()
        }
      }, 1000)
    })
    recorder.onStop((res) => {
      clearInterval(this.recordTimer)
      this.setData({
        isRecording: false,
        hasRecord: !!res.tempFilePath,
        recordFilePath: res.tempFilePath || ''
      })
      if (!res.tempFilePath) {
        wx.showToast({ title: '录音失败', icon: 'none' })
      }
    })
    recorder.onError(() => {
      clearInterval(this.recordTimer)
      this.setData({ isRecording: false })
      wx.showToast({ title: '录音失败', icon: 'none' })
    })
    recorder.start({ duration: this.data.maxRecordDuration * 1000, format: 'mp3' })
  },

  // 停止录音
  stopRecord() {
    const recorder = wx.getRecorderManager()
    recorder.stop()
  },

  // 播放录音
  playRecord() {
    if (!this.data.hasRecord || !this.data.recordFilePath) {
      wx.showToast({ title: '找不到录音，请重新录制', icon: 'none' })
      return
    }
    if (this.data.isPlaying) {
      this.stopAudio()
    }
    const innerAudio = wx.createInnerAudioContext()
    innerAudio.src = this.data.recordFilePath
    innerAudio.play()
    this.setData({ isPlaying: true })
    innerAudio.onEnded(() => {
      this.setData({ isPlaying: false })
      innerAudio.destroy()
    })
    innerAudio.onError(() => {
      wx.showToast({ title: '录音播放失败', icon: 'none' })
      this.setData({ isPlaying: false })
      innerAudio.destroy()
    })
  }
}) 